package main

import(
	"fmt"
	"github.com/gorilla/sessions"
	"net/http"
)

var store = sessions.NewCookieStore([]byte("secretKey"))

func main(){
	http.HandleFunc("/save",SaveSession)
	http.HandleFunc("/get",GetSession)
	err := http.ListenAndServe(":8080",nil)
	if err != nil {
		fmt.Println("Http server failed,error message: ",err)
		return
	}
}

func SaveSession(w http.ResponseWriter,r *http.Request) {

	//获取一个session对象
	session,err := store.Get(r,"sessionName")
	if err != nil {
		http.Error(w,err.Error(),http.StatusInternalServerError)
	}

	session.Values["name"] = "玩具车"
	session.Values["price"] = 50
	session.Values["stock"] = 2

	//保存更改
	session.Save(r,w)

}

func GetSession(w http.ResponseWriter,r *http.Request) {
	session,err := store.Get(r,"sessionName")
	if err != nil {
		http.Error(w,err.Error(),http.StatusInternalServerError)
		return
	}

	name := session.Values["name"]
	price := session.Values["price"]
	stock := session.Values["stock"]

	fmt.Println(name)
	fmt.Println(price)
	fmt.Println(stock)

	session.Options.MaxAge = -1
	session.Save(r,w)

}
//删除
//将session的最大存储时间设置为负数即可，与cookie类似
//session.Options.MaxAge = -1
//session.Save(r,w)